var login = function() {
    this.getHTML = function(baseroot, jparam) {
        if (!baseroot) {
            baseroot = '';
        }
        if (!jparam || $.getObjectAttrCount(jparam) == 0) {
            var jparam = new Object();
            var rows = this.getParams();
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                jparam[row.field] = row.value;
            }
        }
        var html = new Array();
        var id = $.getUUID();
        html.push('<div class="login">');
        html.push('	<div class="login_header">');
        // html.push('		<a href="wdk?action=ecw.page&method=display&page_id=page_login" onclick="toLogin()" ><img src="wdk?action=wdk.pub&method=attachment_download&fileid=frm_banner_logo" ></a>');
        html.push('		<a href="wdk?action=ecw.page&method=display&page_id=page_login&site_id=web"><img src="wdk?action=wdk.pub&method=attachment_download&fileid=frm_banner_logo" ></a>');
        // html.push('		<span class="site_info" onclick="toLogin()"><i style="background-image: url('+ baseroot +'./images/site_address.png);"></i><span id="site_name"></span></span>')
        html.push('	</div>');
        html.push('	<div class="login_content" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=login_bg);">');
        html.push('		<div class="login_content_inner">');
        html.push('			<div class="login_box">');
        html.push('				<div class="login_box_header">');
        html.push('                 <ul>');
        html.push('                     <li class="active">零售户登录</li>');
        // html.push('                     <li onclick="login_Toseller()">商家登录</li>');
        // html.push('                     <li onclick="login_Tostaff()">员工登录</li>');
        html.push('                 </ul>');
        html.push('             </div>');
        html.push('         	<div class="msg_error">');
        html.push('         		<i class="icon_error" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=ecw_icon_icon)"></i>');
        html.push('         		<p class="msg_error_txt"></p>');
        html.push('         	</div>');
        html.push('         	<div class="login_handle">');
        html.push('         	<input type="hidden" id="uuid" name="uuid" >');
        html.push('         		<div class="unit user username">');
        html.push('         			<i class="icon username" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=ecw_icon_icon) "></i>');
        html.push('         			<input type="text" placeholder="请输入用户名" autocomplete="off" name="username" id="login_username" onfocus="login_focusHandle()">');
        html.push('        				<span class="close">x</span>');
        html.push('         		</div>');
        html.push('         		<div class="unit user userpassword">');
        html.push('         			<i class="icon password" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=ecw_icon_icon) "></i>');
        html.push('         			<input type="text" placeholder="请输入密码" autocomplete="new-password" name="userpwd" id="login_userpwd"  onfocus="login_focusHandle()">');
        // html.push('						<input type="text" style="display:none;" placeholder="请输入密码" name="userpwd1" id="login_userpwd1" onfocus="login_focusHandle1()">');
        html.push('						<span class="eyes eyes_open" style="background-image: url(' + baseroot + './images/eyes_open.png);"></span>');
        html.push('						<span class="eyes eyes_close" style="background-image: url(' + baseroot + './images/eyes_close.png);"></span>');
        html.push('         			<span class="close">x</span>');
        html.push('         		</div>');
        html.push('         		<div class="unit code">');
        html.push('         			<div class="code_input">');
        html.push('         				<i class="icon code" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=ecw_icon_icon)"></i>');
        html.push('         				<input type="text" placeholder="请输入验证码" maxlength="4" id="login_identifying_code" onfocus="login_focusHandle()">');
        html.push('         			</div>');
        html.push('         			<div class="login_code" onclick="login_getCode()"><img src="" id="login_idCode"></div>');
        html.push('         		</div>');
        html.push('         		<button class="btn btn_success"  id="login_Toindexbtn">确认登录</button>');
        html.push('         	</div>');
        // html.push('         	<a href="javascript:;" class="login_forget" onclick="login_Toxgmm()">忘记密码?</a>');
        html.push('			</div>');
        html.push('		</div>');
        html.push('	</div>');
        html.push('	<div class="login_footer">');
        html.push('		<p class="login_footer_text">');
        html.push('			<span>Copyright 2023&copy;</span>');
        html.push('			<span>中国烟草总公司山西省公司</span>');
        html.push('     	<span>版权所有 All Rights Reserved</span>');
        html.push('     	<span>晋ICP备2022005568号-8</span>');
        html.push('     </p>');
        html.push('     <i class="login_footer_icon" style="background-image: url(wdk?action=wdk.pub&method=attachment_download&fileid=ecw_icon_icon) "></i>');
        html.push('	</div>');
        html.push('</div>');
        return html.join('');
    };
    this.getDataHTML = function(baseroot, jparam) {
        return this.getHTML(baseroot, jparam)
    };
    this.getParams = function() {
        var jparams = [{
            "name": "网站名称",
            "field": "webname",
            "group": "自定义信息",
            "value": "卷烟订货平台",
            "editor": "text"
        }, {
            "name": "联系电话",
            "field": "phone",
            "group": "自定义信息",
            "value": "",
            "editor": "text"
        }, {
            "name": "省份代码",
            "field": "province",
            "group": "自定义信息",
            "value": "",
            "editor": "text"
        }];
        return jparams;
    };
    this.init = function(jparam) {
        province = jparam.province;
        // 登陆页面 初始化  	
        login_init();
        // 检查手机号
        login_check();
        //输入框动作
        login_inputEvent();
        //登陆首页动作
        login_goIndex();
        //登陆回车动作
        $(document).bind('keydown', 'return', function() {
            if (event.keyCode == 13) {
                $("#login_Toindexbtn").trigger('click');
            }
        });

        //刷新获取验证码      	
        login_getCode();

        $(document).on('click', function(e) {
            var $target = $(e.target);
            if ($target.closest('.eyes_open').length) {
                ispassword = true;
                $('#login_userpwd').get(0).type = 'password';
                $('.eyes_close').show();
                $('.eyes_open').hide();

            } else if ($target.closest('.eyes_close').length) {
                ispassword = false;
                $('.eyes_close').hide();
                $('.eyes_open').show();
                $('#login_userpwd').get(0).type = 'text';
            } else if ($target.closest('.close').length) {
                $target.closest('.close').siblings('input').val('');
                $target.closest('.close').hide();

                if ($target.closest('.close').siblings('#login_userpwd').length) {
                    $('.eyes_close').hide();
                    $('.eyes_open').hide();
                }
                $('#login_userpwd')[0].type = 'text'
            }
        });
    };

};
//全局变量
var login_code = null;
var ispassword = true;
var _uuid = '';
var province = "";
//登陆页面初始化
function login_init() {
    $("#site_name").text($.getSiteName());
    $("#login_identifying_code").val("")
    var username = $.getCookie("_user");
    if (!username) return;
    $("#login_username").val(Base64.decode(username));
    if ($("#login_username").val() != "") {
        $("#login_username").parents(".unit:first").children(".close").show();
        // login_clearText($("#login_username").parents(".unit:first").children(".close"),"click");
    }
    if ($("#login_userpwd").val() != "") {
        if (ispassword) {
            $('.eyes_close').show();
            $('.eyes_open').hide();
        } else {
            $('.eyes_close').hide();
            $('.eyes_open').show();
        }

        $("#login_userpwd").parents(".unit:first").children(".close").show();
        // login_clearText($("#login_userpwd").parents(".unit:first").children(".close"),"click");
    }
}

var str = ''; //定义一个空变量用来存储密码
var num = 1;
window.addEventListener('keyup', function() {
    if (num == 1) {
        $('#login_userpwd')[0].type = 'password'
    }
    num++
})

// 登陆动作
function login_goIndex() {
    $("#login_Toindexbtn").on("click", function() {
        var username = $("input[name=username]").val().trim();
        var password = $("input[name=userpwd]").val().trim();
        var login_identifying_code = $("#login_identifying_code").val();
        if (!username) {
            $(".msg_error").show();
            $(".msg_error").find(".msg_error_txt").text("请输入用户名");
            $(".username").css({
                "border-color": "#c83c14"
            });
            return;
        }
        if (!password) {
            $(".msg_error").show();
            $(".msg_error").find(".msg_error_txt").text("请输入密码");
            $(".userpassword").css({
                "border-color": "#c83c14"
            });
            login_getCode();
            return;
        }
        _uuid = $("#uuid").val();
        $(this).text("登录中");
        $.cuajax({
            url: 'wdk?action=ecw.page&method=login',
            //url:'http://localhost:8080/wdk?action=wdk.pub&method=call_service',
            //url: _PUB_URL2,
            data: {
                // _SRVNAME: 'service.ecw.member'
                _SRVNAME: 'service.ecw.member.v5',
                _SRVMETHOD: 'login',
                _DATA: $.json2str({
                    login_name: username,
                    login_pwd: password,
                    site_id: _SITE_ID,
                    identifying_code: login_identifying_code,
                    serialno: _uuid
                })
            },
            success: function(result) {
                var jres = $.str2json(result);

                //login_successMsg($.json2str(jres.session_info));
                eval(jres.script);
            },
            error: function(result) {
                alert('网络错误！result=' + result);
            }

        })
    })

}

function login_successMsg(res) {
    var _session = $.str2json(res);
    $.setLoginUser(_session);
    $.setHttpOnly(true); //设置HttpOnly
    $.setCookie("_user", Base64.encode($("input[name=username]").val()), 15); //设置15天
    if (_session.reset_pwd_flag === '1') {
        $.page_redirect('page_xgmm');
    } else {
        if (province == "fujian") {
            var pwd = $("input[name=userpwd]").val().trim();
            localStorage.setItem("pwd", Base64.encode(pwd))
            const regex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W_]).{8,}$/;
            if (!regex.test(pwd)) {
                $.page_redirect('page_xgmm', "isWeakPwd=1");
            } else {
                $.go_index();
            }
        } else {
            $.go_index();
        }
    }
}

function login_errorMsg(desc) {
    $(".msg_error").show();
    $(".msg_error").find(".msg_error_txt").text(desc);
    $("#login_userpwd").val("");
    login_getCode();
    if (desc == "账号登录校验失败：账号、密码无效") {
        $(".userpassword").css({
            "border-color": "#c83c14"
        });
    } else {
        $(".code_input").css({
            "border-color": "#c83c14"
        });
        $(".code_input").val("");
    }
    $("#login_Toindexbtn").text("确认登录")
}

String.prototype.trim = function() {
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
//跳转到商家登录
function login_Toseller() {
    $.go_ntm_login();
}
// 跳转到员工登录
function login_Tostaff() {
    $.go_staff_login();
}
//跳转到修改密码
function login_Toxgmm() {
    $.page_open("login_xgmm1")
}
//跳转到登录页
function toLogin() {
    $.go_login();
}
//清除文本操作
function login_clearText(selector, type) {
    $(selector).on(type, function() {
        $(this).siblings("input").val("");
        $(selector).hide();
    })
}

//输入事件
function login_inputEvent() {
    $("input[name='username'],input[name='userpwd']").keyup(function() {
        // if(!!window.ActiveXObject || "ActiveXObject" in window || navigator.userAgent.indexOf("Edge")>-1) return;
        $(this).parents(".unit:first").children(".close").show();
        if ($(this).attr('id') === 'login_userpwd') {
            if (ispassword) {
                $('.eyes_close').show();
                $('.eyes_open').hide();
            } else {
                $('.eyes_close').hide();
                $('.eyes_open').show();
            }
        }
        // login_clearText($(this).parents(".unit:first").children(".close"),"click");
    });
}

//检查手机号
function login_check() {
    $("input[name='username']").on("input propertychange", function() {
        var testUsername = /^[a-zA-Z0-9_-]{1,30}$/;
        var username = $(this).val();
        if ($("input[name='username']").val() == "") {
            return;
        } else {
            if (!(testUsername.test(username))) {
                $(".msg_error").show();
                $(".msg_error").find(".msg_error_txt").text("请输入正确的用户名和密码")
                $(this).parents(".unit:first").css({
                    "border-color": "#c83c14"
                });
            } else {
                $(".msg_error").hide()
                $(this).parents(".unit:first").css({
                    "border-color": "#D5D5D5"
                });
            }
        }
    });
}


//设置10分钟刷新验证码
setInterval(function() {
    login_getCode();
}, 600000)
//获取验证码
var login_index = 0;

function login_getCode() {
    // login_index++;
    // var login_action='wdk?action=ecw.page&method=verifycode&w=135&h=43&'+login_index;
    // $("#login_idCode").attr("src",login_action);

    var uuid = $.getUUID();
    $("#uuid").val(uuid);
    $("#login_idCode").attr("src", "wdk?action=ecw.page&method=verifycode&w=135&h=43&uuid=" + uuid);
}


//聚焦事件
function login_focusHandle(dom) {
    $(".msg_error").hide();
    $(".username,.userpassword,.code_input").css({
        "border-color": "#D5D5D5"
    });
}